package com.vnp.cooking;

import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vnp.cooking.bean.ObjCachlam;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.Common;
import com.vnp.cooking.utils.DecodeUtils;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class TungbuocthuchienActivity extends Activity implements
		OnClickListener {

	PreferenceHelper preferenceHelper;
	LinearLayout mainScroll;
	ImageButton btnBack;

	// dang
	ImageView imgTungbuoc;
	EditText edtTungbuoc;
	TextView titleTungbuoc;
	Dialog dChoose, dChuapost;
	ImageButton btnChoose;

	private static final int PICK_PHOTO = 100;
	private static final int CAPTURE_PHOTO = 200;

	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;

	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_take_photo.jpg";
	String file_path;
	Handler mHandler = new Handler();
	Runnable r = new Runnable() {

		@Override
		public void run() {
			takeImage();
		}
	};
	Runnable rThoat = new Runnable() {

		@Override
		public void run() {
			closeActivity();
		}
	};
	
	Runnable rLuu  = new Runnable() {
		
		@Override
		public void run() {
			luuBuoc();
		}
	};
	boolean uploadSuccess = true;

	// thiet lap image loader
	DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false).cacheOnDisc(true)
			.bitmapConfig(Config.RGB_565).build();

	FrameLayout image;
	Button btnLuubuoc;
	String nameImage = "";
	String urlImage = "";
	public static boolean isCreated;
	int buoclam;

	ObjCachlam objCachlam = new ObjCachlam();

	ProgressBar progressBar;
	String des, urlImg;
	boolean isChange = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tungbuocthuchien);

		preferenceHelper = new PreferenceHelper(this);
		

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnChoose = (ImageButton) findViewById(R.id.btn_themanh);
		imgTungbuoc = (ImageView) findViewById(R.id.img_tungbuoc);
		edtTungbuoc = (EditText) findViewById(R.id.edt_cachlam);
		btnLuubuoc = (Button) findViewById(R.id.btn_luu_buoc);
		titleTungbuoc = (TextView) findViewById(R.id.title_congthuc_buocnau);

		progressBar = (ProgressBar) findViewById(R.id.progressBar1);

		image = (FrameLayout) findViewById(R.id.image);

		edtTungbuoc.setHorizontallyScrolling(false);

		buoclam = BuocThucHienActivity.stepCount + 1;

		init();
		editor();
	}

	void init() {
		if (getIntent().getParcelableExtra("objCachlam") != null) {
			objCachlam = getIntent().getParcelableExtra("objCachlam");
			
		/*	des = objCachlam.getDecriptionStep();
			urlImage = objCachlam.getUrlImageStep();
			*/
			nameImage = objCachlam.getNameImage();
			urlImage = objCachlam.getUrlImageStep();
			if (!urlImage.equals("")) {
				ImageLoader.getInstance().displayImage(
						objCachlam.getUrlImageStep(), imgTungbuoc, options);
			} else {
				imgTungbuoc.setBackgroundResource(R.drawable.bg_dang_ct_02);
			}
			
			edtTungbuoc.setText(objCachlam.getDecriptionStep());
			Log.i("DATA", "Mota: "+objCachlam.getDecriptionStep()+"Anh: "+objCachlam.getUrlImageStep());
			titleTungbuoc.setText("Bước " + objCachlam.getStep());
		} else {
//			titleTungbuoc.setText("Bước " + (buoclam));
			titleTungbuoc.setText("Bước thực hiện");
		}

		btnBack.setOnClickListener(this);
		btnChoose.setOnClickListener(this);
		edtTungbuoc.setOnClickListener(this);
		btnLuubuoc.setOnClickListener(this);
	}

	void editor() {
		edtTungbuoc.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					image.setVisibility(View.VISIBLE);
					KeyboardHelper
							.hideSoftKeyboard(TungbuocthuchienActivity.this);
					edtTungbuoc.setSelection(edtTungbuoc.getText().toString()
							.length());
				}
				return false;
			}
		});
		edtTungbuoc.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				
			}
		});
	}

	void closeActivity() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	@Override
	public void onBackPressed() {
		if (!edtTungbuoc.getText().toString().matches("")) {
			if (isChange == true) {
				KeyboardHelper.hideSoftKeyboard(TungbuocthuchienActivity.this);
				showDialogCanhbaochuapost();
			} else {
				KeyboardHelper.hideSoftKeyboard(TungbuocthuchienActivity.this);
				closeActivity();
			}
		} else {
			KeyboardHelper.hideSoftKeyboard(TungbuocthuchienActivity.this);
			closeActivity();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (!edtTungbuoc.getText().toString().matches("")) {
//				if (!des.matches(edtTungbuoc.getText().toString())||(urlImage.matches(objCachlam.getUrlImageStep())))
				KeyboardHelper.hideSoftKeyboard(TungbuocthuchienActivity.this);
				showDialogCanhbaochuapost();
			} else {
				KeyboardHelper.hideSoftKeyboard(TungbuocthuchienActivity.this);
				closeActivity();
			}

			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_capture_image:
			dChoose.dismiss();
			mHandler.postDelayed(r, 200);
			break;
		case R.id.btn_themanh:
			showDialogChonanh();
			break;

		case R.id.btn_thoat:
			dChoose.dismiss();
			break;

		case R.id.edt_cachlam:
			image.setVisibility(View.GONE);
			break;
		case R.id.btn_luu_buoc:
			/*
			 * if (uploadSuccess == true) { if
			 * (!edtTungbuoc.getText().toString().equals("")) { Log.i("DATA", ""
			 * + urlImage); if (getIntent().getParcelableExtra("objCachlam") !=
			 * null) { for (int i = 0; i < BuocThucHienActivity.objSteps
			 * .size(); i++) { if (i == objCachlam.getStep() - 1) {
			 * BuocThucHienActivity.objSteps.remove(i);
			 * BuocThucHienActivity.objSteps.add(i, new
			 * ObjCachlam(edtTungbuoc.getText() .toString(), urlImage, i,
			 * nameImage)); } } KeyboardHelper.hideSoftKeyboard(this); finish();
			 * } else { BuocThucHienActivity.objSteps.add(new ObjCachlam(
			 * edtTungbuoc.getText().toString(), urlImage, buoclam, nameImage));
			 * KeyboardHelper.hideSoftKeyboard(this); finish(); }
			 * 
			 * } else { Toast.makeText(TungbuocthuchienActivity.this,
			 * "Mô tả bước không được bỏ trống.", Toast.LENGTH_SHORT).show(); }
			 * } else { Toast.makeText(TungbuocthuchienActivity.this,
			 * "Đang cập nhật ảnh...", Toast.LENGTH_SHORT).show(); }
			 */
			luuBuoc();
			

			break;
		default:
			break;
		}
	}
	
	void luuBuoc() {
		if (uploadSuccess == true) {
			if (!edtTungbuoc.getText().toString().equals("")) {
				if (getIntent().getParcelableExtra("objCachlam") != null) {
					for (int i = 0; i < CacBuocThucHienActivity.objSteps
							.size(); i++) {
						if (i == objCachlam.getStep() - 1) {
							CacBuocThucHienActivity.objSteps.remove(i);
							CacBuocThucHienActivity.objSteps.add(i,
									new ObjCachlam(edtTungbuoc.getText()
											.toString(), urlImage, i,
											nameImage));
						}
					}
					KeyboardHelper.hideSoftKeyboard(this);
					closeActivity();
				} else {
					CacBuocThucHienActivity.objSteps.add(new ObjCachlam(
							edtTungbuoc.getText().toString(), urlImage,
							buoclam, nameImage));
					KeyboardHelper.hideSoftKeyboard(this);
					closeActivity();
				}
			} else {
				Toast.makeText(TungbuocthuchienActivity.this,
						"Mô tả bước không được bỏ trống.",
						Toast.LENGTH_SHORT).show();
			}

		} else {
			Toast.makeText(TungbuocthuchienActivity.this,
					"Đang cập nhật ảnh...", Toast.LENGTH_SHORT).show();
		}
	}

	// show dialog sau khi them thanh cong
	public void showDialogChonanh() {
		dChoose = new Dialog(this, R.style.DialogSlideAnim);
		dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dChoose.setContentView(R.layout.dialog_choose_photo);

		Button btnChonanh = (Button) dChoose
				.findViewById(R.id.btn_choose_image);
		Button btnChupanh = (Button) dChoose
				.findViewById(R.id.btn_capture_image);

		Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);
		dChoose.show();
		dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dChoose.setCanceledOnTouchOutside(true);
		dChoose.getWindow().setGravity(Gravity.BOTTOM);
		dChoose.show();

		// setonclick
		btnChonanh.setOnClickListener(this);
		btnChupanh.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
	}

	// chon anh
	public void openGallery() {
		File ff = new File(TEMP_TAKE_IMAGE);
		if (ff.exists())
			ff.delete();
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PICK_PHOTO);
	}

	// chup anh
	public void takeImage() {
		String fileName = "temp.jpg";
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, fileName);
		mCapturedImageURI = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
		startActivityForResult(intent, CAPTURE_PHOTO);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PICK_PHOTO:
				Uri u = (Uri) data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(u, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				file_path = cursor.getString(columnIndex);

				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm = DecodeUtils.decode(TungbuocthuchienActivity.this,
						Uri.parse(file_path), 800, 800);

				if (bm == null) {
					Toast.makeText(TungbuocthuchienActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				imgTungbuoc.setScaleType(ScaleType.CENTER_CROP);
				imgTungbuoc.setImageBitmap(bm);

				// upload image
				uploadImage();

				cursor.close();

				break;
			case CAPTURE_PHOTO:

				String[] projection = { MediaStore.Images.Media.DATA };
				Cursor cursor1 = managedQuery(mCapturedImageURI, projection,
						null, null, null);
				int column_index_data = cursor1
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor1.moveToFirst();
				file_path = cursor1.getString(column_index_data);
				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm1 = DecodeUtils.decode(TungbuocthuchienActivity.this,
						Uri.parse(file_path), 600, 600);
				if (bm1 == null) {
					Toast.makeText(TungbuocthuchienActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				imgTungbuoc.setScaleType(ScaleType.CENTER_CROP);
				imgTungbuoc.setImageBitmap(bm1);

				uploadImage();

				cursor1.close();

				break;
			}
		}
	}

	public String getPath(Uri uri) {

		String[] projection = { MediaStore.Images.Media.DATA };

		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(uri, projection, null, null, null);

		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();
		cursor.close();
		return cursor.getString(column_index);

	}

	void uploadImage() {
		progressBar.setVisibility(View.VISIBLE);
		btnLuubuoc.setVisibility(View.GONE);
		uploadSuccess = false;
		RequestParams params = new RequestParams();
		params.put("user_id", preferenceHelper.getID());
		params.put("recipe_id", preferenceHelper.getRecipeId());
		try {
			params.put("fileUpload", new File(file_path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://anuong.net/api/recipe/imageStep", params,
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						progressBar.setVisibility(View.GONE);
						btnLuubuoc.setVisibility(View.VISIBLE);
						Toast.makeText(TungbuocthuchienActivity.this,
								"Request failed.", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							progressBar.setVisibility(View.GONE);
							btnLuubuoc.setVisibility(View.VISIBLE);
							switch (status) {
							case 200:
								JSONObject data = re.getJSONObject("data");
								Log.i("DATA", "Data return: " + data.toString());
								nameImage = data.getString("name");
								urlImage = data.getString("url");
								uploadSuccess = true;
								/*Toast.makeText(TungbuocthuchienActivity.this,
										"Cập nhật thành công.",
										Toast.LENGTH_SHORT).show();*/
								isChange = true;
								break;
							case 400:

								Toast.makeText(TungbuocthuchienActivity.this,
										"Cập nhật ảnh thất bại (400)",
										Toast.LENGTH_SHORT).show();
								break;
							case 404:
								Toast.makeText(TungbuocthuchienActivity.this,
										"Cập nhật ảnh thất bại (404).",
										Toast.LENGTH_SHORT).show();
								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				});
	}

	void showDialogCanhbaochuapost() {
		dChuapost = new Dialog(TungbuocthuchienActivity.this,
				R.style.DialogSlideAnimLeft);
		dChuapost.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dChuapost.setContentView(R.layout.dialog_thoat_process);

		// khai bao cac thanh phan
		TextView txtArlert = (TextView) dChuapost
				.findViewById(R.id.str_canhbao_thoat);
		Button btnCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_thoat);
		Button btnKoCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_ko_thoat);

		txtArlert
				.setText("Bạn chưa cập nhật các bước thực hiện. Bạn có muốn cập nhật và thoát?");
		btnCapnhatThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dChuapost.dismiss();
				mHandler.postDelayed(rLuu, 200);
			}
		});

		btnKoCapnhatThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dChuapost.dismiss();
				mHandler.postDelayed(rThoat, 200);
			}
		});

		dChuapost.setCanceledOnTouchOutside(true);
		dChuapost.show();
		dChuapost.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dChuapost.getWindow().setGravity(Gravity.CENTER);
	}

}
